package com.example.demo.common;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * Jackson 工具类
 *
 * @author zhaiding
 */
@Slf4j
public class JsonUtils {


    private static final ObjectMapper OBJECT_MAPPER;
    /**
     * DateTime格式化字符串
     */
    private static final String DATA_TIME = "yyyy-MM-dd HH:mm:ss";
    /**
     * Date格式化字符串
     */
    private static final String DATE = "yyyy-MM-dd";

    /**
     * Time格式化字符串
     */
    private static final String TIME = "HH:mm:ss";


    static {
        OBJECT_MAPPER = new ObjectMapper();
        // 设置时区
        OBJECT_MAPPER.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        // 设置时间格式
        OBJECT_MAPPER.setDateFormat(new SimpleDateFormat(DATA_TIME));

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        /* 序列化配置,针对java8 时间 **/
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATA_TIME)));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE)));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(TIME)));

        /* 反序列化配置,针对java8 时间 **/
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATA_TIME)));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE)));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(TIME)));

        /* 声明自定义模块,配置double类型序列化配置 **/
        SimpleModule module = new SimpleModule("DoubleSerializer", new Version(1, 0, 0, "", null, null));

        /* 注册模块 **/
        OBJECT_MAPPER.registerModule(javaTimeModule)
                .registerModule(module)
                .registerModule(new Jdk8Module())
                .registerModule(new ParameterNamesModule())
                // 忽略在json字符串中存在，但是在java对象中不存在对应属性的情况。防止错误
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        ;
    }

    private JsonUtils() {
    }

    public static ObjectMapper getInstance() {
        return OBJECT_MAPPER;
    }


    /**
     * javaBean、列表数组转换为json字符串
     */
    public static String obj2json(Object obj) {
        try {
            return getInstance().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("对象转换为Json失败 {}", e.getMessage(), e);
        }
        return "";

    }

    /**
     * javaBean、列表数组转换为json字符串,忽略空值
     */
    public static String obj2jsonIgnoreNull(Object obj) {
        try {
            ObjectMapper mapper = getInstance().copy();
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("对象转换为Json失败 {}", e.getMessage(), e);
        }
        return "";


    }

    /**
     * json 转JavaBean
     */
    public static <T> T json2pojo(String jsonString, Class<T> clazz) {
        try {
            return getInstance().readValue(jsonString, clazz);
        } catch (IOException e) {
            log.error("json转实体类失败", e);
        }
        return null;
    }


    /**
     * <p>利用jackson的objectMapper将json转换为实体类，支持复杂泛型实体类</p>
     *
     * @param jsonValue    json字符串
     * @param valueTypeRef 要转换的实体类
     * @param <T>          泛型
     * @return 转换后的实体类
     */
    public static <T> T json2pojo(String jsonValue, TypeReference<T> valueTypeRef) {
        try {
            return getInstance().readValue(jsonValue, valueTypeRef);
        } catch (IOException e) {
            log.error("json转实体类失败", e);
        }
        return null;
    }

    /**
     * object 转 JavaBean
     */
    public static <T> T obj2pojo(Object obj, Class<T> clazz) {
        return getInstance().convertValue(obj, clazz);
    }


    /**
     * 与javaBean json数组字符串转换为列表
     */
    public static <T> List<T> json2list(String jsonArrayStr, Class<List<T>> listClass) {

        try {
            return getInstance().readValue(jsonArrayStr, listClass);
        } catch (IOException e) {
            log.error("json数组字符串转换为列表失败", e);
        }
        return Collections.emptyList();
    }

    public static <T> List<T> json2list(String jsonArrayStr, TypeReference<List<T>> typeReference) {
        try {
            return getInstance().readValue(jsonArrayStr, typeReference);
        } catch (IOException e) {
            log.error("json数组字符串转换为列表失败", e);
        }
        return Collections.emptyList();

    }


    /**
     * json字符串转换为map
     */
    public static Map<String, Object> json2map(String jsonString) {
        try {
            ObjectMapper mapper = getInstance().copy();
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return mapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {
            });
        } catch (IOException e) {
            log.error("json数组字符串转换为map失败", e);
        }
        return Collections.emptyMap();
    }


    public static <K, V> Map<K, V> json2map(String jsonData, Class<K> keyType, Class<V> valueType) {
        JavaType javaType = getCollectionType(Map.class, keyType, valueType);
        try {
            return getInstance().readValue(jsonData, javaType);
        } catch (Exception e) {
            log.error("json数组字符串转换为map失败", e);
        }
        return Collections.emptyMap();
    }


    /**
     * 深度转换json成map
     */
    public static Map<String, Object> json2mapDeeply(String json) throws Exception {
        return json2MapRecursion(json, getInstance());
    }

    /**
     * 把json解析成list，如果list内部的元素存在jsonString，继续解析
     */
    @SuppressWarnings("unchecked")
    private static List<Object> json2ListRecursion(String json, ObjectMapper mapper) throws Exception {
        if (json == null) {
            return Collections.emptyList();
        }
        List<Object> list = mapper.readValue(json, List.class);
        List<Object> newList = new ArrayList<>(list.size());
        for (Object obj : list) {
            if (obj instanceof String) {
                String str = (String) obj;
                if (str.startsWith("[")) {
                    obj = json2ListRecursion(str, mapper);
                } else if (obj.toString().startsWith("{")) {
                    obj = json2MapRecursion(str, mapper);
                }
            }
            newList.add(obj);
        }

        return newList;
    }

    /**
     * 把json解析成map，如果map内部的value存在jsonString，继续解析
     */
    @SuppressWarnings("unchecked")
    private static Map<String, Object> json2MapRecursion(String json, ObjectMapper mapper) throws Exception {
        if (json == null) {
            return Collections.emptyMap();
        }
        Map<String, Object> map = mapper.readValue(json, Map.class);

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object obj = entry.getValue();
            if (obj instanceof String) {
                String str = ((String) obj);

                if (str.startsWith("[")) {
                    List<?> list = json2ListRecursion(str, mapper);
                    map.put(entry.getKey(), list);
                } else if (str.startsWith("{")) {
                    Map<String, Object> mapRecursion = json2MapRecursion(str, mapper);
                    map.put(entry.getKey(), mapRecursion);
                }
            }
        }

        return map;
    }


    /**
     * 获取泛型的Collection Type
     *
     * @param collectionClass 泛型的Collection
     * @param elementClasses  元素类
     * @return JavaType Java类型
     */
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return OBJECT_MAPPER.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

}